﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kelper.Domain.Models;

namespace Kelper.Infrastructure.Helpers
{
    public class IngredientCloud
    {
        public IList<KeyValuePair<Ingredient, double>> IngredientsAndUsageSpread { get; set; }

        public IngredientCloud() { }
        public IngredientCloud(IEnumerable<KeyValuePair<Ingredient, int>> ingredients)
        {
            IngredientsAndUsageSpread = new List<KeyValuePair<Ingredient, double>>();
            if (ingredients.Any())
            {
                double average = ingredients.Average(i => i.Value);
                foreach (KeyValuePair<Ingredient, int> kv in ingredients)
                {
                    double value = kv.Value / average;
                    IngredientsAndUsageSpread.Add(new KeyValuePair<Ingredient, double>(kv.Key, value));
                }

                Shuffle(IngredientsAndUsageSpread);
            }
        }

        private void Shuffle<T>(IList<T> list)
        {
            Random r = new Random();
            for (int i = 0; i < list.Count; i++)
            {
                int i1 = r.Next(list.Count),
                    i2 = r.Next(list.Count);

                T tmp = list[i1];
                list[i1] = list[i2];
                list[i2] = tmp;
            }
        }
    }
}